
package com.kcsj.service.user;

import com.kcsj.dao.User.EmployeeDao;
import com.kcsj.dao.User.UserDao;
import com.kcsj.domain.user.Employee;
import com.kcsj.domain.user.User;
import com.kcsj.util.Condition;
import com.kcsj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */

public class EmployeeService {
    private static EmployeeService EmployeeService = new EmployeeService();
    public static EmployeeService getInstance(){return EmployeeService;}

    private static EmployeeDao employeeDao = EmployeeDao.getInstance();

    private EmployeeService(){}

    public Collection<User> findAll(List<Condition> conditionList) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        Collection<User> users = employeeDao.findAll(conn, conditionList);
        users.removeIf(user -> user.getRole().getName().equals("超级管理员"));
        JdbcHelper.close(conn);
        return users;
    }

    public User find(Integer id) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        User user = employeeDao.find(id, conn);
        JdbcHelper.close(conn);
        return user;
    }

    public Employee findInfo(Integer id) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        Employee employee = employeeDao.findInfo(id, conn);
        JdbcHelper.close(conn);
        return employee;
    }

    public void addUserOfEmployee(User user) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        //向user表中插入一个元组
        user.setType("员工");
        user.setActivationStatus(true);
        employeeDao.add(user,conn);
        JdbcHelper.close(conn);
    }


    public void updateInfo(User user) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        try{
            UserDao.getInstance().update(user,conn);
            Employee employee = (Employee)user.getActor();
            employeeDao.update(employee,conn);
            conn.commit();
        }catch (SQLException e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            conn.setAutoCommit(false);
            JdbcHelper.close(conn);
        }
    }


    public boolean delete(Integer id) throws SQLException {
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        boolean delete = false;
        try{
            delete = employeeDao.delete(id,conn);
            delete = UserDao.getInstance().delete(id, conn);
            conn.commit();
        }catch (SQLException e){
            e.printStackTrace();
            conn.rollback();
        }finally {
            conn.setAutoCommit(false);
            JdbcHelper.close(conn);
        }
        return delete;
    }
}
